package com.cxw.healthserver.service

import com.cxw.healthserver.entity.Token
import com.cxw.healthserver.response.BaseResponse
import com.cxw.healthserver.response.LoginResponse
import com.cxw.healthserver.utils.UUIDUtils
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class AuthService {
    private val validity = 3600L * 24 * 30 * 1000

    @Autowired
    private lateinit var userService: UserService

    @Autowired
    private lateinit var tokenService: TokenService

    fun login(username: String, password: String): BaseResponse<LoginResponse> {
        val user = userService.getUserByUsernameAndPassword(username, password)
        if (user == null) {
            val user2 = userService.getUserByUsername(username)
            return if (user2 == null) {
                BaseResponse.fail("用户不存在")
            } else {
                BaseResponse.fail("密码错误")
            }
        }


        val userId = user.id
        var token = tokenService.getTokenByUserId(userId)
        val newTokenValue = UUIDUtils.generateUUID() // 生成新token值
        val rows: Int
        if (token == null) {
            token = Token()
            token.userid = userId
            token.token = newTokenValue
            token.expirationTime = System.currentTimeMillis() + validity  //token有效期30天
            rows = tokenService.insertToken(token)
        } else {
            token.userid = userId
            token.token = newTokenValue
            token.expirationTime = System.currentTimeMillis() + validity  //token有效期30天
            rows = tokenService.updateToken(token)
        }
        return if (rows >= 0) {
            BaseResponse.success(LoginResponse(token.token, token.expirationTime))
        } else {
            BaseResponse.fail("登录失败(rows:${rows})")
        }
    }

    fun checkToken(token:String?):BaseResponse<Token>{
        return tokenService.checkToken(token)
    }
}